package io.renren.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.renren.common.utils.Constant;
import io.renren.common.utils.HttpReqUtil;
import io.renren.entity.ApEntity;
import io.renren.entity.EslRefreshLogEntity;
import io.renren.entity.SysDictEntity;
import io.renren.param.*;
import io.renren.service.*;
import io.renren.vo.ApsVo;
import io.renren.vo.BindApVo;
import io.renren.vo.EslReturnVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("eslWorkingService")
public class EslWorkingServiceImpl implements EslWorkingService {

    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private EslService eslService;
    @Autowired
    private ApService apService;
    @Autowired
    private EslRefreshLogService eslRefreshLogService;

    /**
     * 为企业分配基站
     *
     * @param compId
     * @param apMac
     * @return
     */
    public Boolean bindAp(String compId, String apMac) {
        Boolean result = false;
        List<ApsVo> apsVos = new ArrayList<>();


        ApEntity apEntity = apService.queryByApMac(apMac);
        if (apEntity == null) {
            return result;
        }

        List<ApEntity> apEntities = apService.queryByUser(compId);
        for (ApEntity entity : apEntities) {
            //ap已绑定过，不需要重新下发
            if (apMac.equals(entity.getMac())) {
                result = true;
                return result;
            } else {
                ApsVo aps1 = new ApsVo();
                aps1.setMac(entity.getMac());
                aps1.setAllow_bind_v1esl(entity.getAllowBindV1esl() == 0 ? false : true);
                apsVos.add(aps1);
            }
        }

        //查询企业对应的esl-working url
        SysDictQueryParam param = new SysDictQueryParam();
        param.setCode("cloud");
        param.setName(Constant.SysDictName.ESL_WORKING_URL.getValue());
        SysDictEntity sysDictEntity = sysDictService.queryByNameCode(param);
        if (StringUtils.isNotBlank(sysDictEntity.getValue())) {
            String url = sysDictEntity.getValue() + "/" + compId + Constant.BIND_AP_URI;

            BindApVo vo = new BindApVo();
            ApsVo aps = new ApsVo();
            aps.setMac(apMac);
            aps.setAllow_bind_v1esl(apEntity.getAllowBindV1esl() == 0 ? false : true);
            apsVos.add(aps);

            vo.setAps(apsVos);

            //绑定ap
            String jsonStr = JSONUtil.parseObj(vo).toString();
            String res = HttpReqUtil.doPut(url, jsonStr);

            EslReturnVo returnVo = JSONUtil.toBean(res, EslReturnVo.class);
            if (0 == returnVo.getStatusNo()) {
                result = true;
            }

        }
        return result;
    }

    /**
     * 取消绑定基站
     *
     * @param compId
     * @param apMac
     * @return
     */
    public Boolean unBindAp(String compId, String apMac) {
        Boolean result = false;

        //查询企业对应的esl-working url
        SysDictQueryParam param = new SysDictQueryParam();
        param.setCode("cloud");
        param.setName(Constant.SysDictName.ESL_WORKING_URL.getValue());
        SysDictEntity sysDictEntity = sysDictService.queryByNameCode(param);
        if (StringUtils.isNotBlank(sysDictEntity.getValue())) {
            String url = sysDictEntity.getValue() + "/" + compId + Constant.UNBIND_AP_URI + "/" + apMac;
            //解绑p
            String res = HttpReqUtil.doDelete(url);

            EslReturnVo returnVo = JSONUtil.toBean(res, EslReturnVo.class);
            if (0 == returnVo.getStatusNo()) {
                result = true;
            }
        }
        return result;
    }

    /**
     * AP心跳
     *
     * @param param
     */
    public void apHeartBeat(ApHeartBeatParam param) {
//    public void apHeartBeat(List<ApHeartBeatData> param) {
//        log.debug("ApHeartBeatParam = {}", param);
        apService.batchSave(param);
    }

    /**
     * ESL心跳
     *
     * @param param
     */
    public void eslHeartBeat(EslHeartBeatParam param) {
//    public void eslHeartBeat(List<EslHeartBeatData> param) {
//        log.debug("EslHeartBeatParam = {}", param);
        eslService.batchSave(param);
    }

    /**
     * 刷新价签
     *
     * @param param
     */
    public Boolean refreshEsl(RefreshEslParam param) {
//    public Boolean refreshEsl(RefreshEslParam param) {

        List<String> deskEslList = new ArrayList<>();
        deskEslList.add("56-A4-15-C5");
        deskEslList.add("56-A4-03-C5");
        deskEslList.add("56-93-7B-C5");
        deskEslList.add("56-A3-CA-C5");
        deskEslList.add("56-A3-2C-C5");
        deskEslList.add("56-A4-23-C5");
        deskEslList.add("56-A4-04-C5");
        deskEslList.add("56-A3-88-C5");
        deskEslList.add("56-A4-14-C5");
        deskEslList.add("56-A4-21-C5");


        List<String> roomEslList = new ArrayList<>();
        roomEslList.add("57-D6-EF-8C");
        roomEslList.add("57-D7-21-8C");


        log.debug("RefreshEslParam = {}", JSONUtil.parseObj(param));

        Boolean result = false;

        SysDictQueryParam dictParam = new SysDictQueryParam();
        param.setBack_url(Constant.EW_CALL_BACK_URL);

        JSONObject json = new JSONObject("{\n" +
                "\t\"nfc\": {\n" +
                "\t\t\"standard_content\": \"AA7RAQpVAWJhaWR1LmNvbQ==\",\n" +
                "\t\t\"private_content\": \"\"\n" +
                "\t},\n" +
                "\t\"auto_refresh\": \"false\"\n" +
                "}");

        param.setStore_config(json);

        //查询企业对应的esl-working url
        dictParam.setCode("cloud");
        dictParam.setName(Constant.SysDictName.ESL_WORKING_URL.getValue());
        SysDictEntity sysDictEntity = sysDictService.queryByNameCode(dictParam);
        if (StringUtils.isNotBlank(sysDictEntity.getValue())) {
            String url = sysDictEntity.getValue() + "/" + param.getCompId() + Constant.REFRESH_ESL_URI;
//            url = "http://159.75.242.167:8081/api/ew/httpHandler";

            Map<String, Object> map = new HashMap<>();
            List<RefreshEslParam> params = new ArrayList<>();
            params.add(param);
            map.put("data", params);


            //刷新esl
            String jsonStr = JSONUtil.parseObj(map).toString();


//            String jsonStr = "{     \n" +
//                    "    \"data\": [       \n" +
//                    "    { \n" +
//                    "        \"esl_id\": \"56-93-3D-C5\", \n" +
//                    "        \"sid\": \"3984799300029882\",             \n" +
//                    "        \"priority\": 10,    \n" +
//                    "        \"back_url\": \"http://172.16.0.10:8081/backurl\", \n" +
//                    "        \"template\": \"PROMO_480800750-BLACK-WHITE-RED\",            \n" +
//                    "        \"BookingPerson1\":\"\",\n" +
//                    "        \"Nextmeeting\":\"\",\n" +
//                    "        \"qrCode\":\"www.huawei.com\",\n" +
//                    "        \"BookingPerson2\":\"\",\"date4\":\"1135\",\"date3\":\"1135\",\"date2\":\"1135\",\"date1\":\"1135\",\"NowMeeting\":\"\",\"theme\":\"红树林\",\n" +
//                    "        \"name\":\"黄小明\",\n" +
//                    "        \"store_config\":{\n" +
//                    "             \"nfc\":{\n" +
//                    "                    \"standard_content\":\"AA7RAQpVAWJhaWR1LmNvbQ==\",\n" +
//                    "                    \"private_content\":\"\"\n" +
//                    "        }\n" +
//                    "        }\n" +
//                    "       \n" +
//                    "        }     \n" +
//                    "    ] \n" +
//                    "}";

//            String jsonStr = "{     \n" +
//                    "    \"data\": [       \n" +
//                    "    { \n" +
//                    "        \"esl_id\": \"57-D7-21-8C\", \n" +
//                    "        \"sid\": \"3984799300029882\",             \n" +
//                    "        \"priority\": 10,    \n" +
//                    "        \"back_url\": \"http://172.16.0.10:8081/backurl\", \n" +
//                    "        \"template\": \"PROMO1_480800750-BLACK-WHITE-RED\",            \n" +
//                    "        \"department\":\"国内事业部\",\n" +
//                    "        \"EnglishName\":\"Leason Zhang\",\n" +
//                    "        \"JobNumber\":\"HS0375\",\n" +
//                    "        \"status\":\"会议中\",\n" +
//                    "        \"NowMeeting\":\"金融风险\",\n" +
//                    "        \"Nextmeeting\":\"投资品鉴会\",\n" +
//                    "        \"qrCode\":\"http://www.huawei.com\",\n" +
//                    "        \"BookingPerson1\":\"张三\",\n" +
//                    "        \"BookingPerson2\":\"张伟\",\n" +
//                    "        \"date1\":\"800\",\n" +
//                    "        \"date2\":\"930\",\n" +
//                    "        \"date3\":\"1800\",\n" +
//                    "        \"date4\":\"1930\",\n" +
//                    "        \"DateTime\":\"2021年12月06日 星期一\",\n" +
//                    "        \"theme\":\"红树林\",\n" +
//                    "        \"name\":\"张磊鑫\",\n" +
//                    "        \"store_config\":{\n" +
//                    "             \"nfc\":{\n" +
//                    "                    \"standard_content\":\"AA7RAQpVAWJhaWR1LmNvbQ==\",\n" +
//                    "                    \"private_content\":\"\"\n" +
//                    "        }\n" +
//                    "        }\n" +
//                    "       \n" +
//                    "        }     \n" +
//                    "    ] \n" +
//                    "}";

//            jsonStr = jsonStr.replace("张磊鑫", param.getName() + "5");
////            jsonStr = jsonStr.replace("57-D7-21-8C", param.getEsl_id());
////            jsonStr = jsonStr.replace("57-D7-21-8C", "56-A3-88-C5");//门牌esl
//            jsonStr = jsonStr.replace("3984799300029882", RandomUtil.randomNumbers(10));
////            jsonStr = jsonStr.replace("PROMO_480800750-BLACK-WHITE-RED", param.getTemplate());
//            jsonStr = jsonStr.replace("PROMO1_480800750-BLACK-WHITE-RED", "NORMAL_6409601160-BLACK-WHITE-RED");//门牌模板
//            jsonStr = jsonStr.replace("张三", param.getBookingPerson1());
//            jsonStr = jsonStr.replace("张伟", param.getBookingPerson2());
//            jsonStr = jsonStr.replace("金融风险", param.getNowMeeting());
//            jsonStr = jsonStr.replace("投资品鉴会", param.getNextmeeting());
//            jsonStr = jsonStr.replace("红树林", param.getTheme());

            //记录日志
            EslRefreshLogEntity eslRefreshLogEntity = EslRefreshLogEntity.createFor(url, jsonStr, param);
            eslRefreshLogService.save(eslRefreshLogEntity);

            String res = HttpReqUtil.doPut(url, jsonStr);

            EslReturnVo returnVo = JSONUtil.toBean(res, EslReturnVo.class);
            if (0 == returnVo.getStatusNo()) {
                result = true;
            }

        }
        return result;
    }

    /**
     * 异步刷新结果
     *
     * @param param
     */
    public void refreshNotify(RefreshNotifyParam param) {
        log.debug("RefreshNotifyParam = {}", JSONUtil.parseObj(param));

    }
}
